<template>
  <a-table :columns="columns" :data-source="props.data" :pagination="pagination">
    <template #bodyCell="{column,record}">
      <template v-if="column.key === 'action'">
        <a-button type="primary" v-if="props.isRelation" @click="relationClick(record.id)">关联</a-button>
        <a-button type="primary" v-else @click="cancelClick(record.id)">取消关联</a-button>
      </template>
    </template>
  </a-table>
</template>
<script setup lang="ts">

import type {ArticleDataType, LiteratureDataType} from "@/util/publicType";
import type {ColumnsType} from "ant-design-vue/es/table";
import {ref, watch} from "vue";
import type {AxiosResponse} from "axios";
import {cancelRelationArticle, cancelRelationLiterature, relationArticle, relationLiterature} from "@/api/api";
import {message} from "ant-design-vue";

const props = defineProps(["data", "meta", "isRelation", "isArticle", "dictId"]);
const emit = defineEmits(["onMetaChange"])

// 分页
const pagination = ref({
  total: props.meta.total,
  current: props.meta.currentPage,
  // 每页条数
  pageSize: props.meta.perSize,
  // 是否快速跳转
  showQuickJumper: true,
  // 是否可以改变page和size
  showSizeChanger: true,
  // 总条数
  showTotal: (total: number) => "总条数：" + total,
  //页码改变或者条数的回调
  onChange: (p: number, ps: number) => {
    emit("onMetaChange", p, ps);
  },
});

// 当分页变化，重新执行操作
watch(props.meta, (newMeta) => {
  pagination.value = {
    ...pagination.value,
    current: newMeta.currentPage,
    // 每页条数
    pageSize: newMeta.perSize,
    // 总条数
    total: newMeta.total,
  }
})

// 取消关联
const cancelClick = (id: string) => {
  let request: Promise<AxiosResponse>;
  if (props.isArticle) {
    request = cancelRelationArticle(id);
  } else {
    request = cancelRelationLiterature(id);
  }
  request.then(() => {
    message.success("已取消关联").then(() => {
      // 刷新当前页面
      window.location.reload();
    })
  }, err => message.error(err));
}

// 关联操作
const relationClick = (id: string) => {
  let request: Promise<AxiosResponse>;
  if (props.isArticle) {
    request = relationArticle(props.dictId, {article_id: id});
  } else {
    request = relationLiterature(props.dictId, {literature_id: id})
  }
  request.then(() => {
    message.success("关联成功").then(() => {
      window.location.reload();
    })
  }, err => message.error(err))
}

const columns: ColumnsType<LiteratureDataType | ArticleDataType> = [
  {
    title: "名字",
    dataIndex: "name",
    key: "name",
    align: "center",
    width: "26%"
  },
  {
    title: "阅读数",
    dataIndex: "visit_num",
    key: "visit_num",
    align: "center"
  },
  {
    title: "所属字典",
    dataIndex: "dictName",
    key: "dictName",
    align: "center"
  },
  {
    title: "操作",
    dataIndex: "action",
    key: "action",
    align: "center",
  }
]
</script>